/**
 * @file mqtt_client.c
 * @brief MQTT客户端模块实现
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mosquitto.h>
#include "mqtt_client.h"

// MQTT客户端实例
static struct mosquitto *g_mosq = NULL;

// MQTT主题
static char g_topic[128] = {0};

/**
 * @brief MQTT连接回调函数
 */
static void on_connect(struct mosquitto *mosq, void *obj, int rc) {
    if (rc == 0) {
        printf("Connected to MQTT broker\n");
    } else {
        fprintf(stderr, "Failed to connect to MQTT broker: %s\n", mosquitto_connack_string(rc));
    }
}

/**
 * @brief MQTT断开连接回调函数
 */
static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) {
    printf("Disconnected from MQTT broker\n");
}

int mqtt_client_init(const char *broker_address, const char *topic) {
    if (broker_address == NULL || topic == NULL) {
        return -1;
    }

    // 初始化mosquitto库
    mosquitto_lib_init();

    // 创建MQTT客户端实例
    g_mosq = mosquitto_new(NULL, true, NULL);
    if (g_mosq == NULL) {
        fprintf(stderr, "Failed to create mosquitto instance\n");
        mosquitto_lib_cleanup();
        return -1;
    }

    // 设置回调函数
    mosquitto_connect_callback_set(g_mosq, on_connect);
    mosquitto_disconnect_callback_set(g_mosq, on_disconnect);

    // 连接到MQTT服务器
    if (mosquitto_connect(g_mosq, broker_address, 1883, 60) != MOSQ_ERR_SUCCESS) {
        fprintf(stderr, "Failed to connect to MQTT broker\n");
        mosquitto_destroy(g_mosq);
        mosquitto_lib_cleanup();
        return -1;
    }

    // 启动网络线程
    if (mosquitto_loop_start(g_mosq) != MOSQ_ERR_SUCCESS) {
        fprintf(stderr, "Failed to start mosquitto network thread\n");
        mosquitto_disconnect(g_mosq);
        mosquitto_destroy(g_mosq);
        mosquitto_lib_cleanup();
        return -1;
    }

    // 保存主题
    strncpy(g_topic, topic, sizeof(g_topic) - 1);

    return 0;
}

int mqtt_client_publish(float temperature, float humidity) {
    if (g_mosq == NULL) {
        return -1;
    }

    // 构建JSON格式的消息
    char message[128];
    snprintf(message, sizeof(message), "{\"temperature\":%.1f,\"humidity\":%.1f}", temperature, humidity);

    // 发布消息
    int rc = mosquitto_publish(g_mosq, NULL, g_topic, strlen(message), message, 0, false);
    if (rc != MOSQ_ERR_SUCCESS) {
        fprintf(stderr, "Failed to publish message: %s\n", mosquitto_strerror(rc));
        return -1;
    }

    return 0;
}

void mqtt_client_cleanup(void) {
    if (g_mosq != NULL) {
        mosquitto_loop_stop(g_mosq, true);
        mosquitto_disconnect(g_mosq);
        mosquitto_destroy(g_mosq);
        g_mosq = NULL;
    }
    mosquitto_lib_cleanup();
}